package com.zxt.servlet;

import com.zxt.bean.AdminBean;
import com.zxt.dao.MysqlDao;
import com.zxt.mapper.NameMapper;
import com.zxt.utils.DruidConnUtil;
import com.zxt.utils.JDBCTemplate;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * Created by XiaoQiAng on 2015/11/8.
 */
public class AdminLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        checkLogin(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        checkLogin(request, response);
    }

    protected void checkLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        HashMap<String,String> hashMap = new HashMap<>();
        AdminBean adminBean = new AdminBean();
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        if (userName.equals("")) {
            hashMap.put("username","Please input username");
        } else {
            adminBean.setName(userName);
        }
        if (password.equals("")) {
            hashMap.put("password","Please input password");
        } else {
            adminBean.setPassword(password);
        }
        if (!hashMap.isEmpty()) {
            request.setAttribute("err",hashMap);
            request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
        } else {
            Object[] objects = {adminBean.getName(), adminBean.getPassword()};
            JDBCTemplate jdbcTemplate = new JDBCTemplate(DruidConnUtil.getDataSource());
            NameMapper nameMapper = new NameMapper();
            List list = jdbcTemplate.checkData(new MysqlDao().adminLoginCheck(), objects, nameMapper);
            if (list.size() == 1) {
                request.getSession().setAttribute("username",adminBean.getName());
                request.getRequestDispatcher("jsp/index.jsp").forward(request, response);
            } else {
                hashMap.put("login", "login filed");
                request.setAttribute("err",hashMap);
                request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
            }
        }
    }
}